/*
 *  Copyright (C) 2010 glauco
 *
 *  This program is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  This program is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU General Public License for more details.
 *
 *  You should have received a copy of the GNU General Public License
 *  along with this program.  If not, see <http://www.gnu.org/licenses/>.
 */

package org.balisunrise.bindings;

import java.util.HashMap;
import java.util.Map;
import org.balisunrise.common.BindingException;

/**
 *
 * @author Glauco
 */
public class BPLChild {

    private Map<String, BindingPropertyListener> bpls;
    private BindingPropertyListener parent;
    private Object source;

    //private BindingPropertyListener bpl;

    public BPLChild(BindingPropertyListener parent, Object source)
            throws BindingException {

        bpls = new HashMap<String, BindingPropertyListener>();
        this.parent = parent;
        this.source = source;
    }

    public void addBinding(String property, Binding binding, int fire)
            throws BindingException {

        String[] props;

        if(property.contains("."))
            props = property.split("\\.");
        else
            props = new String[]{property};

        String prop = props[0];
        BindingPropertyListener bpl;

        if(bpls.containsKey(prop))
            bpl = bpls.get(prop);
        else{
            bpl = new BindingPropertyListener(parent, source);
            bpls.put(prop, bpl);
        }

        bpl.addBinding(property, binding, fire);
    }

    public void removeBinding(Binding binding){
        for (BindingPropertyListener bpl : bpls.values()) {
            bpl.removeBinding(binding);
        }
    }

    public void register(Object source) throws BindingException{
        for (BindingPropertyListener bpl : bpls.values()) {
            bpl.setSource(source);
            bpl.activate();
        }
    }

    public void unRegister(){
        for (BindingPropertyListener bpl : bpls.values()) {
            bpl.deactivate();
        }
    }

    public void sourceChanged(Object source) throws BindingException{
        this.source = source;
        for (BindingPropertyListener bpl : bpls.values()) {
            bpl.setSource(source);
        }
    }
}
